package com.qf.service.impl;

import com.qf.entity.Student;
import com.qf.service.StudentService;
import com.qf.utils.StudentDataStore;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {


    @Override
    public List<Student> add(Student student) {
        //静态的唯一id
        Integer id = StudentDataStore.idgenerator++;
        student.setId(id);

        //就student放入list中
        StudentDataStore.stuList.add(student);
        return StudentDataStore.stuList;
    }

    @Override
    public void edit(Student student) {
        //获取学生的id
        Integer id = student.getId();
        int index = -1;
        for (int i=0;i<StudentDataStore.stuList.size();i++){
            //判断id和数组中每个元素的id是否相等
            if(id.equals(StudentDataStore.stuList.get(i).getId())){
                index = i;
                break;
            }
        }
        if(index!=-1){
            StudentDataStore.stuList.set(index,student);
        }
    }

    @Override
    public List<Student> list() {
        //返回数组
        return StudentDataStore.stuList;
    }

    @Override
    public void delete(Integer id) {
        int index = -1;
        for (int i=0;i<StudentDataStore.stuList.size();i++){
            //判断id和数组中每个元素的id是否相等
            if(id.equals(StudentDataStore.stuList.get(i).getId())){
                index = i;
                break;
            }
        }
        if(index!=-1 && index<StudentDataStore.stuList.size()) {
            StudentDataStore.stuList.remove(index);
        }
    }

    @Override
    public Student findbyId(Integer id){
        int index = -1;
        for (int i=0;i<StudentDataStore.stuList.size();i++){
            //判断id和数组中每个元素的id是否相等
            if(id.equals(StudentDataStore.stuList.get(i).getId())){
                index = i;
                break;
            }
        }
        if(index != -1) {
            return StudentDataStore.stuList.get(index);
        }
        return null;
    }
}
